//
//  YXMineAddressViewController.m
//  CreditCard
//
//  Created by 杨旭 on 2017/12/24.
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "YXMineAddressViewController.h"
#import "YXMineAddressCell.h"
#import "YXMineNewAddressViewController.h"
#import "YXAddressModel.h"
#import "YXMachineMaterialViewController.h"
#import "YXAddressModel.h"
#define defaultTag 1990

@interface YXMineAddressViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UIButton *tempBtn;
}
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) UIButton *addAddressBtn;
@property (nonatomic ,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) YXAddressModel *model;

@end

@implementation YXMineAddressViewController

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (UIButton *)addAddressBtn {
    if (!_addAddressBtn) {
        _addAddressBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _addAddressBtn.frame = CGRectMake(0, kScreenHeight -50 - 64, kScreenWidth, 50);
        _addAddressBtn.backgroundColor = color_globalColor;
        [_addAddressBtn setTitle:@"添加新地址" forState:(UIControlStateNormal)];
        [_addAddressBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_addAddressBtn addTarget:self action:@selector(addAddressBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _addAddressBtn;
}
- (void)addAddressBtnAction {
    YXMineNewAddressViewController *newAddVC = [[YXMineNewAddressViewController alloc] init];
    newAddVC.title = @"新增收货地址";
    [self.navigationController pushViewController:newAddVC animated:YES];
}


- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:(CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64-50)) style:(UITableViewStylePlain)];
        _tableView.backgroundColor = color_backColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"YXMineAddressCell" bundle:nil] forCellReuseIdentifier:@"YXMineAddressCell"];
    }
    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestDataAddressList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"地址管理";
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.addAddressBtn];
}

- (void)requestDataAddressList {
    
//    http://121.196.210.134:8082/mpos/wx/addr_list.do
    NSString *urlStr = @"addr_list.do";
    YXUserInfoModel *model = [YXUserInfoManager getUserInfo];
    NSDictionary *parameter = @{@"sessionId":model.sessionId};
    [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
//        NSLog(@"请求成功%@",responseObject);
        if (REQUESTDATASUCCESS) {
            NSMutableArray *arr = [NSMutableArray array];
            self.dataArr = [YXAddressModel mj_objectArrayWithKeyValuesArray:responseObject[@"body"]];
            for (YXAddressModel *model in self.dataArr) {
                if (self.dataArr.count > 0) {
                    [arr addObject:model.defaults];
                }
            }
            if ([arr containsObject:@"1"]) {
                NSInteger index = [arr indexOfObject:@"1"];
                [self.dataArr exchangeObjectAtIndex:0 withObjectAtIndex:index];
                NSLog(@"-- index -- %ld",index);
            }else {
                NSLog(@"不存在");
            }

            NSLog(@"%@",arr);
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        NSLog(@"请求失败%@",error);
        [self showAlertWith:@"维护中，请稍等！"];

    }];
    
}


#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YXMineAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YXMineAddressCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArr[indexPath.section];
    cell.tag = 1990 + indexPath.section;
    
    if ([cell.model.defaults isEqualToString:@"0"]) {
        cell.selectBtn.selected = NO;
    }else {
        if (indexPath.section == 0) {
            cell.selectBtn.selected = YES;
        }
    }
   
    
    // 设置默认地址
//    __weak typeof(cell) weakSelf = cell;
    [cell setClickDefaultBtnBlock:^(YXAddressModel *model,UIButton *btn) {
      
        //    http://121.196.210.134:8082/mpos/wx/updateAddress.do
        NSString *str = [[NSString stringWithFormat:@"updateAddress.do?sessionId=%@&addresseeName=%@&phone=%@&province=%@&city=%@&area=%@&detailedAddress=%@&isChoice=%@&addressId=%@", [YXUserInfoManager getUserInfo].sessionId, model.addresseeName, model.phone, model.province == nil ? @"" : model.province,model.city == nil ? @"" :model.city,model.area == nil ? @"" : model.area,model.detailedAddress,@"0",model.addressId] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        [BX_NetWorkManager requestForGETWithUrl:str parameter:nil success:^(id responseObject) {
            if (REQUESTDATASUCCESS) {
                NSLog(@"%@",responseObject);
                tempBtn.selected = NO;
                tempBtn = btn;
                btn.selected = YES;
                [self showTostMessage:@"设置成功！"];
                [self requestDataAddressList];
                
            }
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
            [self showTostMessage:@"设置失败！"];

        }];
        

    }];
    
    
    // 编辑
    [cell setClickEditBtnBlock:^(YXAddressModel *model) {
        YXMineNewAddressViewController *newAddVC = [[YXMineNewAddressViewController alloc] init];
        newAddVC.model = model;
        newAddVC.title = @"修改收货地址";
        [self.navigationController pushViewController:newAddVC animated:YES];
    }];
    
    // 删除
    [cell setClickDeletedBtnBlock:^(YXAddressModel *model) {
        
        UIAlertController *action = [UIAlertController alertControllerWithTitle:@"是否确认删除该地址？" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
      
        UIAlertAction *alert = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {

            //    http://121.196.210.134:8082/mpos/wx/deleteAddress.do
            NSString *urlStr = @"deleteAddress.do";
            NSDictionary *parameter = @{@"sessionId":[YXUserInfoManager getUserInfo].sessionId,@"addressId":model.addressId};
            [BX_NetWorkManager requestForPOSTWithUrl:urlStr parameter:parameter success:^(id responseObject) {
                
                [self requestDataAddressList];
                [self showTostMessage:@"删除成功！"];
            } failure:^(NSError *error) {
                [self showTostMessage:@"删除失败！"];
            }];
        }];
        
        [action addAction:alert];
        
        UIAlertAction *can = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [action addAction:can];
        [self presentViewController:action animated:YES completion:nil];


    }];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    YXAddressModel *model = self.dataArr[indexPath.section];
//    YXMachineMaterialViewController *mmVC = [[YXMachineMaterialViewController alloc] init];
//    mmVC.addressModel = model;
    YXMineAddressCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.selectAddressBlock(cell.addressLab.text);
    [self.navigationController popViewControllerAnimated:YES];
}

@end
